package com.sanjiayi.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.Hashtable;
@Component
public class WeChatPayQRCodeUtil {
    /**
     * 根据微信支付链接生成二维码的 Base64 编码
     *
     * @param weixinUrl 微信支付链接，如：weixin://wxpay/bizpayurl?pr=xxxx
     * @return 二维码的 Base64 编码
     * @throws Exception 异常
     */
    public static String generateWeChatPayQrCodeBase64(String weixinUrl) throws Exception {
        // 二维码图片的宽度和高度
        int width = 300;
        int height = 300;

        // 设置二维码的编码格式
        Hashtable<EncodeHintType, String> hints = new Hashtable<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        // 创建二维码生成器
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(weixinUrl, BarcodeFormat.QR_CODE, width, height, hints);

        // 创建BufferedImage对象，来存储二维码图像
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                // 如果二维码的当前像素是黑色，则设置为黑色，否则设置为白色
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0x000000 : 0xFFFFFF);
            }
        }

        // 将二维码图片转换为 Base64 编码
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "PNG", byteArrayOutputStream);
        byte[] imageBytes = byteArrayOutputStream.toByteArray();
        return "data:image/png;base64," + Base64.getEncoder().encodeToString(imageBytes);
    }
}
